"""
The is doc
"""


import logging
import functools

from traceback import format_exc
from traceback_with_variables import iter_exc_lines

from rest_framework import status

from .json_response import json_response_utf8

logger = logging.getLogger("log")


# 小程序 只能 展示 七个字的错误
class NoAccess(Exception):
    """doc"""

    def __init__(self, *args: object, msg="", **kwargs: dict) -> None:
        self.code = -10001
        self.msg = f"no access: need login, please access /login. {msg}"

        super().__init__(*args, **kwargs)


class AdminLoginFail(Exception):
    """doc"""

    def __init__(self, *args: object, msg="", **kwargs: dict) -> None:
        self.code = -10002
        self.msg = f"admin login fail. {msg}"

        super().__init__(*args, **kwargs)


class ParamsErr(Exception):
    """doc"""

    def __init__(self, *args: object, msg="", **kwargs: dict) -> None:
        self.code = -10003
        self.msg = f"params error. {msg}"

        super().__init__(*args, **kwargs)


class ValueErr(Exception):
    """doc"""

    def __init__(self, *args: object, msg="", **kwargs: dict) -> None:
        self.code = -10004
        self.msg = f"value error. {msg}"

        super().__init__(*args, **kwargs)


class NullErr(Exception):
    """doc"""

    def __init__(self, *args: object, msg="", **kwargs: dict) -> None:
        self.code = -10005
        self.msg = f"var can not be null. {msg}"

        super().__init__(*args, **kwargs)


class ObjExist(Exception):
    """doc"""

    def __init__(self, *args: object, msg="", **kwargs: dict) -> None:
        self.code = -20002
        self.msg = f"same obj exist. {msg}"

        super().__init__(*args, **kwargs)


class ObjNotExist(Exception):
    """doc"""

    def __init__(self, *args: object, msg="", **kwargs: dict) -> None:
        self.code = -20002
        self.msg = f"obj does not exist. {msg}"

        super().__init__(*args, **kwargs)


class IncorrectFormat(Exception):
    """doc"""

    def __init__(self, *args: object, msg="", **kwargs: dict) -> None:
        self.code = -20006
        self.msg = f"Incorrect Format. {msg}"

        super().__init__(*args, **kwargs)


class UrlInValid(Exception):
    """doc"""

    def __init__(self, *args: object, msg="", **kwargs: dict) -> None:
        self.code = -20007
        self.msg = f"url must start with https. {msg}"

        super().__init__(*args, **kwargs)


class WxOpenidExist(Exception):

    """doc"""

    def __init__(self, *args: object, msg="", **kwargs: dict) -> None:
        self.code = -30002
        self.msg = f"openid exist. {msg}"

        super().__init__(*args, **kwargs)


class OnlyReadAttr(Exception):

    """doc"""

    def __init__(self, *args: object, msg="", **kwargs: dict) -> None:
        self.code = -30003
        self.msg = f"OnlyReadAttr. {msg}"

        super().__init__(*args, **kwargs)


def app_try(func):
    """捕获异常, 并抛出统一错误提示"""

    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except Exception as _exception:
            lines = []
            lines += list(iter_exc_lines(_exception))
            lines.append(format_exc())
            logger.fatal("\n".join(lines))
            _msg = getattr(
                _exception,
                "msg",
                getattr(_exception, "message", "系统错误"),
            )
            return json_response_utf8(
                {
                    "code": getattr(_exception, "code", -1),
                    "exception": f"{type(_exception).__name__}",
                    "msg": f"{str(_exception)}: {_msg}",
                    "detail": getattr(_exception, "detail", "系统错误"),
                },
                status=status.HTTP_400_BAD_REQUEST,
            )

    return wrapper
